<!-- src/views/BorrowManagementView.vue -->
<template>
  <div class="borrow-management-view">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>📚 借阅管理</h2>
          <el-button type="primary" @click="loadAllData" :loading="loading">
            刷新列表
          </el-button>
        </div>
      </el-header>
      <el-main>
        <el-card>
          <template #header>
            <div class="card-header">
              <span>当前借阅记录 ({{ activeRecords.length }})</span>
            </div>
          </template>

          <BorrowRecordsTable
            :records="activeRecords"
            :loading="loading"
            :show-return-button="true"
            :returning-id="returningId"
            @return="handleReturnRecord"
          />
        </el-card>

        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>历史借阅记录 ({{ historicalRecords.length }})</span>
              <el-button
                type="success"
                size="small"
                @click="loadAllHistoricalRecords"
                :loading="historicalLoading"
                icon="Refresh"
              >
                加载全部
              </el-button>
            </div>
          </template>

          <el-input
            v-model="searchBorrower"
            placeholder="输入借阅人姓名搜索历史记录"
            style="width: 300px; margin-bottom: 20px;"
            @keyup.enter="searchHistoricalRecords"
            clearable
            @clear="loadAllHistoricalRecords"
          />

          <BorrowRecordsTable
            :records="historicalRecords"
            :loading="historicalLoading"
          />
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { createBorrowService } from '@/services/borrowServiceFactory'
import { ElMessage, ElMessageBox } from 'element-plus'
import BorrowRecordsTable from '@/components/BorrowRecordsTable.vue'

export default {
  name: 'BorrowManagementView',
  components: {
    BorrowRecordsTable
  },
  setup() {
    const borrowService = createBorrowService()
    const activeRecords = ref([])
    const historicalRecords = ref([])
    const loading = ref(false)
    const historicalLoading = ref(false)
    const returningId = ref(null)
    const searchBorrower = ref('')

    const loadActiveRecords = async () => {
      try {
        loading.value = true
        activeRecords.value = await borrowService.getActiveRecords()
        console.log('当前借阅记录加载完成:', activeRecords.value)
      } catch (error) {
        console.error('加载当前借阅记录失败:', error)
        ElMessage.error('加载当前借阅记录失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }

    const loadAllHistoricalRecords = async () => {
      try {
        historicalLoading.value = true
        const allRecords = await borrowService.getAllRecords()
        historicalRecords.value = allRecords.filter(record => record.returned)
        console.log('历史借阅记录加载完成:', historicalRecords.value)
      } catch (error) {
        console.error('加载历史借阅记录失败:', error)
        ElMessage.error('加载历史借阅记录失败: ' + error.message)
      } finally {
        historicalLoading.value = false
      }
    }

    const searchHistoricalRecords = async () => {
      if (!searchBorrower.value.trim()) {
        await loadAllHistoricalRecords()
        return
      }

      try {
        historicalLoading.value = true
        const records = await borrowService.getRecordsByBorrower(searchBorrower.value.trim())
        historicalRecords.value = records.filter(record => record.returned)
        console.log('搜索历史记录完成:', historicalRecords.value)
      } catch (error) {
        console.error('搜索历史记录失败:', error)
        ElMessage.error('搜索历史记录失败: ' + error.message)
      } finally {
        historicalLoading.value = false
      }
    }

    const loadAllData = async () => {
      await loadActiveRecords()
      await loadAllHistoricalRecords()
    }

    const handleReturnRecord = async (recordId) => {
      try {
        await ElMessageBox.confirm(
          '确定要归还这本书吗？',
          '归还确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }
        )

        returningId.value = recordId
        console.log('开始归还操作，记录ID:', recordId)

        await borrowService.returnBook(recordId)
        ElMessage.success('归还成功！')

        await loadAllData()

      } catch (error) {
        if (error !== 'cancel') {
          console.error('归还操作失败:', error)
          ElMessage.error('归还失败: ' + (error.message || '未知错误'))
        }
      } finally {
        returningId.value = null
      }
    }

    onMounted(() => {
      loadAllData()
    })

    watch(searchBorrower, (newVal, oldVal) => {
      if (newVal === '' && oldVal !== '') {
        loadAllHistoricalRecords()
      }
    })

    return {
      activeRecords,
      historicalRecords,
      loading,
      historicalLoading,
      returningId,
      searchBorrower,
      loadAllData,
      loadAllHistoricalRecords,
      searchHistoricalRecords,
      handleReturnRecord
    }
  }
}
</script>

<style scoped>
.borrow-management-view {
  height: 100vh;
}
.el-header {
  background-color: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
</style>